#
# This file is a part of the open-eBackup project.
# This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
# If a copy of the MPL was not distributed with this file, You can obtain one at
# http://mozilla.org/MPL/2.0/.
#
# Copyright (c) [2024] Huawei Technologies Co.,Ltd.
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
# EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
# MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
#

from common.const import CMDResult, ExecuteResultEnum
from common.common import execute_cmd
from common.common_models import SubJobDetails, ActionResult
from common.logger import Logger
from db2.restore.db2_restore_base import Db2RestoreBase
from db2.comm.util.common_util import Db2CommonUtil
from db2.comm.const import Db2JsonConstant
from db2.comm.backup_param_parse import ParameterBackupParse
from db2.restore.single.single_db_restore import SingleRestore

LOGGER = Logger().get_logger(filename="db2.log")


class HaRestore(Db2RestoreBase):
    def __init__(self, task_name, pid, job_id, sub_job_id, param_dict):
        super().__init__(task_name, pid, job_id, sub_job_id, param_dict)
        self.param_util = ParameterBackupParse(pid, job_id, sub_job_id, param_dict)
        self.restore_handle = SingleRestore(task_name, pid, job_id, sub_job_id, param_dict)

    def allow_restore_in_local_node(self):
        LOGGER.info("Start Ha allow_restore_in_local_node")
        user_name = self.param_util.get_database_user_name(Db2JsonConstant.JOB_TARGETENV_NODES_0_AUTH_AUTHKEY)
        exec_cmd = f"su - {user_name} -c 'db2level'"
        ret_code, std_out, std_err = execute_cmd(exec_cmd)
        if ret_code != CMDResult.SUCCESS.value:
            return Db2CommonUtil.build_action_result(
                code=ExecuteResultEnum.INTERNAL_ERROR.value, message="No primary nodes")
        return self.restore_handle.allow_restore_in_local_node()

    def exec_restore_pre_job(self):
        return self.restore_handle.exec_restore_pre_job()

    def exec_restore(self):
        return self.restore_handle.exec_restore()

    def exec_restore_post_job(self):
        return self.restore_handle.exec_restore_post_job()

    def report_progress(self):
        return self.restore_handle.report_progress()

    def output_action_result(self, action_ret: ActionResult):
        super(HaRestore, self).output_action_result(action_ret)